import React from 'react'
import {connect} from 'react-redux'
import {Form, message, Spin, Button, Tooltip, Icon} from "antd";
const FormItem = Form.Item;
import borrowService from "containers/loan-billing/borrow-and-return.service";
import customField from "share/customField";
import {messages, queryCurrencyPrecision, deepFullCopy} from "share/common";
import RelatedApplication from 'containers/request/new-request/related-application';
import travelUtil from "containers/request/travel-request/travelUtil";
import chooserDate from "share/chooserData";
import Chooser from "components/chooser";
import baseService from "share/base.service";
const formItemLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 14, offset: 1},
};

class EditLoan extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      info: {},
      formInfo: {},
      signEnable: false,
      signCompanyOIDs: [],
      loading: false,
      copyDefaultValues: [],
      referenceApplicationOID: '',
      saveLoading: false,
      propsParams: {
        precision: queryCurrencyPrecision(props.company.baseCurrency)
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.editShow === this.props.editShow)
      return;
    if (!nextProps.editShow) {
      this.props.form.resetFields();
      this.setState({
        info: {},
        formInfo: {},
        signEnable: false,
        signCompanyOIDs: [],
        copyDefaultValues: [],
        referenceApplicationOID: '',
        saveLoading: false
      });
      return !1;
    }
    this.props.form.resetFields();
    this.setState({
      info: nextProps.info,
      formInfo: deepFullCopy(nextProps.formInfo),
      referenceApplicationOID: nextProps.info.referenceApplicationOID,
      propsParams: {
        precision: queryCurrencyPrecision(nextProps.info.currencyCode)
      }
    },() => {
      const { info } = this.state;
      // this.isCounterSignEnable();
      this.copyDefault(info);
    });
  }

  copyDefault = (value) => {
    let copy = [];
    copy.checkedChange = this.checkedChange;//设置监听
    //添加更改状态单子不可编辑 部门，成本中心，申请人，参与人
    if(value.sourceApplicationOID){
      value.customFormValues = travelUtil.setDisabledValues(value.customFormValues);
    }
    value.customFormValues.map(field => {
      copy.push({
        value: field.value,
        messageKey: field.messageKey,
        formValueOID: field.formValueOID,
        fieldOID: field.fieldOID,
        fieldName: field.fieldName,
        required: field.required,
        formType: 2005,
        showName: {name: field.showValue},
        initValue: {value: field.value, name: field.showValue},
        showValue: field.showValue,
        dataSource: field.dataSource
      });
    });
    this.setState({copyDefaultValues: copy});
  };

  checkedChange = (field,value,allValue) => {
    const { enableDepCompany } = this.props, { setFieldsValue, resetFields, getFieldsValue } = this.props.form;
    let copy = this.state.copyDefaultValues;
    let isChangeCompany = false, isChangeCurrencyCode = false, isChangeDepartment = false;
    let { formInfo, info, propsParams } = this.state;
    let customForm = this.props.params.loanBillOID ? info.customFormValues || [] : formInfo.customFormFields || [];
    let id = this.props.params.loanBillOID ? 'formValueOID' : 'fieldOID';
    copy.map(res => {
      if (res.messageKey === field.messageKey && res.fieldOID === field.fieldOID) {
        if ((field.messageKey === 'select_cost_center' || field.messageKey === 'select_department') && (res.value !== value)) {
          res.showName = allValue;
          field.messageKey === 'select_department' && (isChangeDepartment = true);
        }
        if (field.messageKey === 'select_company') {
          isChangeCompany = true;
        }
        if (field.messageKey === 'currency_code') {
          isChangeCurrencyCode = true;
          propsParams.precision = queryCurrencyPrecision(value);
        }
        res.value = value;
      }
    });
    //切换了公司要清空成本中心
    if(isChangeCompany){
      customForm.map(i => {
        if (i.messageKey === 'select_cost_center' && !i.isReadOnly) {
          this.setState({ loading: true });
          baseService.checkCostCenterNeedEmpty().then(res => {
            this.setState({ loading: false });
            if (res.data.visible) {
              // setFieldsValue({[i.fieldOID]: undefined});
              setFieldsValue({[i.formValueOID]: undefined});
              copy.map(item => {
                if (item.messageKey === 'select_cost_center') {
                  item.showName = undefined;
                  item.value = '';
                }
              })
            }
          });
        }
        if (i.messageKey === 'select_department' && !i.isReadOnly && enableDepCompany === 'OPEN') {
          // setFieldsValue({[i.fieldOID]: undefined});
          setFieldsValue({[i.formValueOID]: undefined});
          copy.map(item => {
            if (item.messageKey === 'select_department') {
              item.showName = undefined;
              item.value = '';
            }
          })
        }
      });
      // 清空收款单位
      const venMaster = customForm.filter(item => {
        return item.messageKey === 'venMaster'
      })[0];
      if (venMaster) {
        resetFields(venMaster.fieldOID);
      }
    }
    if (isChangeDepartment) {
      customForm.map(i => {
        if (i.messageKey === 'select_cost_center' && !i.isReadOnly) {
          this.setState({ loading: true });
          baseService.checkCostCenterNeedEmpty().then(res => {
            this.setState({ loading: false });
            if (res.data.visible) {
              setFieldsValue({[i.fieldOID]: undefined});
              copy.map(item => {
                if (item.messageKey === 'select_cost_center') {
                  item.showName = undefined;
                  item.value = '';
                }
              })
            }
          });
        }
      });
    }
    if(isChangeCurrencyCode){
      let setData = {};
      copy.map(item => {
        if (item.messageKey === 'total_budget') {
          let temp = Number(this.filterMoney(getFieldsValue()[item[id]],propsParams.precision,true).replace(/,/mg,''));
          item.value = temp;
          setData[item[id]] = temp;
        }
      });
      setFieldsValue(setData);
    }
    this.setState({copyDefaultValues:copy, propsParams});
  };

  //获取加签人
  isCounterSignEnable = () => {
    const { info } = this.state;
    this.setState({loading:true});
    let params = {
      companyOID: this.props.company.companyOID,
      formOID: this.state.formInfo.formOID,
      counterSignType: 'enableAddSignForSubmitter',
    };
    console.log('info', info)
    Promise.all([
      borrowService.postAddSignEnableScope(params),
      borrowService.getJobInfo(info.jobId)
    ]).then(res => {
      if (res[0].data.enabled) {
        this.setState({
          signEnable: res[0].data.enabled,
          signCompanyOIDs: res[0].data.approvalAddSignScope.companyOIDs,
          loading: false,
          jobInfo: res[1].data
        });
      } else {
        this.setState({
          loading: false,
          jobInfo: res[1].data
        });
      }
    }).catch(() => {
      this.setState({loading:false});
      message.error(messages('loan-billing.key25')/*系统异常*/);
    });
    borrowService.postAddSignEnableScope(params).then(res =>{
      if (res.data.enabled) {
        this.setState({
          signEnable: res.data.enabled,
          signCompanyOIDs: res.data.approvalAddSignScope.companyOIDs,
          loading: false
        });
      }else{
        this.setState({loading:false});
      }
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

   // 当“是否显示关联”组件的switch的状态发生变化时触发
   onSwitchChange = (field, isSwitchOn) => {
    const { form } = this.props;
    const map = item => {
      if (item.fieldOID === field.fieldOID) {
        return {
          ...item,
          isSwitchOn
        }
      }
      return item
    }
    
    this.setState({
      defaultValues: {
        ...this.state.defaultValues,
        custFormValues: 
          (this.state.defaultValues.custFormValues||[]).map(map)
      },
      formInfo: {
        ...this.state.formInfo,
        customFormFields: 
          (this.state.formInfo.customFormFields||[]).map(map)
      }
    }, () =>{ 
      form.validateFields([field.fieldOID], { force: true });
    })
  }

  //渲染表格
  rendForm = (field,index, formField = null) => {
    const { formInfo, info, copyDefaultValues, propsParams, jobInfo } = this.state;
    const { getFieldDecorator, getFieldsValue } = this.props.form;
    let label = field.fieldName;
    if (field.messageKey === 'number') {
      JSON.parse(field.fieldContent || '{}').unit && (label = `${field.fieldName}(${JSON.parse(field.fieldContent || '{}').unit})`);
    }
    let rules = [];
    if (formField.messageKey === 'public.assembly') {
      rules = this.getRules(formField);
    } else {
      rules = this.getRules(field);
    }
    let formDetailValues = formInfo;
    formDetailValues.currencyCode = info.currencyCode;
    formDetailValues.applicantOID = info.applicant && info.applicant.userOID;
    formDetailValues.customFormFields = info.customFormValues;
    if (formField.fieldTips && formField.fieldTips.length > 0) {
      label = <span>{label}&nbsp;
        <Tooltip title={formField.fieldTips}>
          <Icon type="question-circle-o" />
        </Tooltip>
      </span>
    }
    console.log("info", info)
    return (
      <div key={index}>
        {index === 0 && field.messageKey !== 'applicant' && (
          this.relatedApplication()
        )}
        <FormItem {...formItemLayout} label={label || ' '} key={field.formValueOID} colon={!!label}>
          {getFieldDecorator(field.formValueOID, {
            rules,
            valuePropName: field.messageKey === 'switch' ? 'checked' : 'value',
            initialValue: customField.getInitialValue(field)
          })(
            customField.renderForm({
              field: formField.messageKey === 'public.assembly' ? Object.assign({}, {...formField}, {...field}) : field,
              formDetail: formDetailValues,
              copyValue: copyDefaultValues,
              propsParams,
              formValues: getFieldsValue(),
              jobId: info.jobId,
              // jobInfo,
              type: 3,
              onSwitchChange: this.onSwitchChange
            })
          )}
        </FormItem>
        {index === 0 && field.messageKey === 'applicant' && (
          this.relatedApplication()
        )}
      </div>
    )
  };

  //获取控件规则
  getRules = (field) => {
    let maxLength = undefined;
    switch (field.messageKey) {
      case 'remark':
      case 'textArea':
      case 'text_area':
        maxLength = 200;
        break;
      case 'title':
      case 'input':
        maxLength = 50;
        break;
      default :
        maxLength = undefined;
        break;
    }
    const rules = [];
    if (field.messageKey === 'public.assembly') {
      if (field.isHidden) {
        if (field.isSwitchOn) {
          rules.push({
            required: field.required,
            message: messages('common.can.not.be.empty', {name: field.fieldName})
          });
          if (field.required) {
            rules.push({
              validator: (rule, value, callback) => {
                if ([null, '[]'].includes(value)) {
                  callback('请填写完整');
                } else {
                  callback();
                }
              }
            });
          }
        } else {
          rules.push({
            required: false,
            message: messages('common.can.not.be.empty', {name: field.fieldName})
          });
        }
      } else {
        rules.push({
          required: field.required,
          message: messages('common.can.not.be.empty', {name: field.fieldName})
        });
        if (field.required) {
          rules.push({
            validator: (rule, value, callback) => {
              if ([null, '[]'].includes(value)) {
                callback('请填写完整');
              } else {
                callback();
              }
            }
          });
        }
      }
    } else {
      rules.push({
        required: field.required,
        message: messages('common.can.not.be.empty', {name: field.fieldName})
      });
      if (field.required) {
        rules.push({
          validator: (rule, value, callback) => {
            if ([null, '[]'].includes(value)) {
              callback('请填写完整');
            } else {
              callback();
            }
          }
        });
      }
    }
    maxLength && rules.push({
      max: maxLength,
      message: messages('common.max.characters.length', {max: maxLength})
    });
    (field.messageKey === 'out_participant_name' || field.messageKey === 'external_participant_name') && rules.push({
      validator: (rule, value, callback) => {
        let emptyItem = '';
        value && value.map(item => {
          if (!item.name) {
            emptyItem = messages('loan-billing.key61')/*姓名*/;
            return
          }
          if (!item.certificateNo) {
            emptyItem = messages('loan-billing.key62')/*证件号*/;
          }
        });
        if (!emptyItem) {
          callback();
          return
        }
        callback(messages('common.can.not.be.empty', {name: emptyItem}))
      }
    });
    return rules;
  };

  //关联申请单控件调用
  relatedApplication = () => {
    const { formInfo, info } = this.state;
    return (
      <RelatedApplication formOID={this.props.formInfo.formOID}
                          formInfo={formInfo}
                          applicantOID={this.props.user.userOID}
                          disabled={true}
                          applicationOID={this.props.params.loanBillOID}
                          info={info}
                          isEdit={true}
                          changeHandle={(value) => {this.setState({referenceApplicationOID: value[0] && value[0].applicationOID ? value[0].applicationOID : ''})}}/>
    )
  };

  //保存
  handleSave = () => {
    let customFormFields = this.state.info.customFormValues;
    let isHaveValidate = false;
    let isContainer = false;
    let needValidateForms = ['venMasterSwitch', 'linkage_switch'];
    customFormFields && customFormFields.map(item => {
      if (~needValidateForms.indexOf(item.messageKey)) {
        let info = this.props.form.getFieldValue(item.formValueOID);
        if (info) {
          info.callBackSubmit = !info.callBackSubmit;
          this.props.form.setFieldsValue({[item.formValueOID]: info},() => {
            let isPassValid = true;
            let values = this.props.form.getFieldValue(item.formValueOID);
            if (values) {
              isPassValid = !isPassValid || values.isPassValid;
            }
            isContainer = true;
            isHaveValidate = isPassValid;
          });
        }
      }
      if (item.messageKey === 'public.assembly') {
        const { customFormFields: realCustomFormFields } = this.props.formInfo;
        realCustomFormFields.map((field) => {
          if (item.fieldOID === field.fieldOID) {
            if (field.isHidden && !field.isSwitchOn) {
              this.props.form.setFieldsValue({[item.formValueOID]: '[]'});
            }
          }
        });
      }
    });
    
    setTimeout(() => {
      if((isContainer && isHaveValidate) || (!isContainer)){
        this.delayHandleSave();
      }
    },10);
  };


  //处理保存
  delayHandleSave = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { info, referenceApplicationOID } = this.state;
        const { requestInfo } = this.props;
        let params = JSON.parse(JSON.stringify(info));
        params.customFormValues = this.getCustomFormValues(values);
        params.referenceApplicationOID = referenceApplicationOID;
        params.countersignApproverOIDs = this.props.form.getFieldsValue().addSign;
        let applicantOIDs = null;
        let companyOIDs = null;
        params.customFormValues.map(item => {
          if(item.messageKey === 'applicant'){
            applicantOIDs = item.value;
          }
          if(item.messageKey === 'select_company'){
            companyOIDs = item.value;
          }
        });
        params.applicantOID = applicantOIDs ? applicantOIDs : (params.applicantOID ? params.applicantOID : this.props.user.userOID);
        params.companyOID = companyOIDs ? companyOIDs : (params.companyOID ? params.companyOID : this.props.company.companyOID);
        if(Object.keys(requestInfo).length){
          params.referenceApplicationOID = requestInfo.applicationOID;
          params.directCreate = 1;
        }
        const { customFormFields: realCustomFormFields } = this.props.formInfo;
        this.setState({saveLoading: true});
        if (info.applicantOID !== info.createdBy) {
          info.isProxy = 1
        }
        borrowService.handleSave(params).then(() => {
          this.setState({saveLoading: false});
          message.success(messages('common.save.success', {name: ''}));
          this.props.close(true);
        }).catch(e => {
          this.setState({saveLoading: false});
          let error = e.response.data;
          if (error.validationErrors && error.validationErrors.length) {
            message.error(`${error.validationErrors[0].message}`);
          } else {
            message.error(`${error.message}`);
          }
        })
      }
    });
  };

  getCustomFormValues = (values) => {
    let customFormValues = this.props.params.loanBillOID ? JSON.parse(JSON.stringify(this.state.info.customFormValues)) : JSON.parse(JSON.stringify(this.state.formInfo.customFormFields));
    customFormValues.map(item=> {
      Object.keys(values).map(key => {
        if (key === item.fieldOID || key === item.formValueOID) {
          item = customField.formatFormValue(item, values[key]);
        }
      })
    });
    return customFormValues;
  };

  render(){
    const { info, loading, formInfo, signEnable, signCompanyOIDs, saveLoading } = this.state;
    const { getFieldDecorator } = this.props.form;
    const customFields = deepFullCopy(this.props.formInfo.customFormFields)
    let signPerson = [];
    info.countersignApproverNames && info.countersignApproverNames.map(item => {
      signPerson.push({userOID: item.userOID, fullName: item.fullName})
    });
    let signName = customField.getSignNameForSubmitter(formInfo && formInfo.customFormPropertyMap);
    let chooserItem = chooserDate.user;
    if(signCompanyOIDs.length > 0){
      chooserItem.url = `/api/users/v3/search?corporationOID=${signCompanyOIDs}`;
    }
    return(
      <div className='edit-loan'>
        <div style={{fontSize:18}}>{info.formName ? info.formName : ''}</div>
        <Spin spinning={loading}>
          <Form>
            <div style={{margin: '0 0 20px 30%'}}>{customField.instructionsTag(formInfo.customFormPropertyMap)}</div>
            {
              info.customFormValues && info.customFormValues.map((field, index) => {
                let formField = customFields.filter((item) => item.fieldOID === field.fieldOID)
                return this.rendForm(field, index, formField[0])
              })
            }
            {/* {signEnable && (
              <FormItem {...formItemLayout} label={signName} key="addSign">
                {getFieldDecorator('addSign', {
                  rules: [{
                    required: formInfo.customFormPropertyMap && formInfo.customFormPropertyMap.enableCounterSignForSubmitterMustWriter === 'true',
                    message: messages('common.can.not.be.empty', {name: signName})
                  }],
                  initialValue: signPerson
                })(
                  <Chooser selectorItem={chooserItem}
                           valueKey="userOID"
                           labelKey="fullName"
                           onlyNeed="userOID"
                           listExtraParams={{roleType: 'TENANT'}}
                           showArrow={formInfo.customFormPropertyMap && formInfo.customFormPropertyMap.countersignType === '2'}
                           newline/>
                )}
              </FormItem>
            )} */}
          </Form>
        </Spin>
        <div className="footer-operate" style={{backgroundColor:'#ffffff',left:'0px'}}>
          <Button type="primary"  onClick={this.handleSave} style={{margin:'0px 10px'}} loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    company: state.login.company,
    user: state.login.user,
    enableDepCompany: state.setting.enableDepCompany
  }
}

const WrappedEditLoan = Form.create()(EditLoan);

export default connect(mapStateToProps)(WrappedEditLoan);
